<template>
	<!-- 我的赛事 -->
	<view>
		<view class="bgWhite">
			<view class="uni-padding-wrap uni-common-mt">
				<uni-segmented-control :current="current" :values="items" style-type="text"
					:active-color="activeColor" @clickItem="onClickItem" />
			</view>
			<view class="topSearch">
				<uni-search-bar style="width: 670rpx;" @clear="onclear()" @confirm="onconfirm()" clearButton="auto" cancelButton="none" v-model="queryParam.name"></uni-search-bar>
				<uni-icons type="settings" size="30" @click="showSearchPop"></uni-icons>
			</view>
		</view>


		<view class="content" v-if="current==0">
			<view>
				<view class="bgWhite">
					<view class="matchItem" @click="goSignDetail(item)" v-for="(item,index) in list" :key="index">
						<view class="leftImg">
							<text class="matchType type2" v-if="item.type=='0'">独立赛</text>
							<text class="matchType type1" v-if="item.type=='1'">联赛</text>
							<image mode="aspectFit" :src="item.bgImgUrl"></image>
						</view>
						<view class="rightWen">
							<view class="name">{{item.name}}</view>
							<text class="time" style="margin: 0;" v-if="item.groupName">报名参赛队：{{item.groupName}}</text>
							<view class="time" style="margin: 0;">开始时间：{{item.beginTime.substring(0, 10)}}</view>
							<view class="time" style="margin: 0;">结束时间：{{item.endTime.substring(0, 10)}}</view>
							<text class="status s01" v-if="item.auditStatus=='1'">已提交</text>
							<text class="status s02" v-if="item.auditStatus=='2'">审核通过</text>
							<text class="status s03" v-if="item.auditStatus=='3'">未通过</text>
							<text class="status s04" v-if="item.auditStatus=='4'">已取消</text>
						</view>
					</view>
					<view style="padding: 30rpx 30rpx 60rpx;" v-show="total>10">
						<uni-pagination @change="changePagination" :show-icon="true" pageSize='10' :current="queryParam.pageNum" :total="total" title="标题文字" />
					</view>
					<view class="nodata" v-if="list.length==0">
						<image mode="aspectFit" src="/static/nodata.png"></image>
						<text>暂无报项</text>
					</view>				
				</view>
			</view>
		</view>

		<view class="billcontent" v-if="current==1">
			<!-- 订单 -->
			<uni-collapse>
				<uni-collapse-item title-border="none" :border="false" class="baoItem" :show-animation="true" v-for="(b,index) in billList" :key="index">
					<template v-slot:title>
						<view class="bold">{{b.cptName}}</view> 
						<view class="pp">订单编号：<text>{{b.code}}</text></view>
						<view class="pp">下单时间：<text>{{b.commitTime}}</text></view>
						<view class="pp" v-if="b.totalPayAmount">已付金额：<text class="orange">￥{{b.totalPayAmount}}</text></view>
						<view class="pp" v-if="b.totalAmount">订单金额：<text class="orange" style="font-size: 34rpx;">￥{{b.totalAmount}}</text></view>
					</template> 
					<view class="collapseBody" style="padding-bottom:20rpx">
						<view class="pp" v-if="b.payTime">付款时间：<text>{{b.payTime}}</text></view>
						<view class="pp" v-if="b.payType">付款方式：
							<text v-if="b.payType=='0'">会员卡支付</text>
							<text v-else-if="b.payType=='1'">微信支付</text>
							<text v-else-if="b.payType=='2'">线下支付</text>
						</view>
						<view class="pp" v-if="b.needPay=='0'">状态：<text class="green">免费订单</text></view>
						<view class="pp" v-else>付款状态：
						<!-- 0 未支付  1 线下支付待核销  2 付款中 3 线下支付已核销/已支付 4 退款中 5 已退款 6 线下退款待核销' -->
							<text v-if="b.payStatus=='0'" class="orange">待支付</text>
							<text v-if="b.payStatus=='1'" class="green">线下支付</text>
							<text v-if="b.payStatus=='2'" class="orange">付款中</text>
							<text v-if="b.payStatus=='3'" class="green">已支付</text>
							<text v-if="b.payStatus=='4'" class="red">退款中</text>
							<text v-if="b.payStatus=='5'" class="red">已退款</text>
							<text v-if="b.payStatus=='6'">退款核销中</text>
						</view>
						<view class="pp" v-if="b.auditStatus!='0'">审核状态：
							<text v-if="b.auditStatus=='1'" class="orange">待审核</text>
							<text v-if="b.auditStatus=='2'" class="green">审核通过</text>
							<text v-if="b.auditStatus=='3'" class="red">审核未通过</text>
							<text v-if="b.auditStatus=='4'" class="gary">已取消</text>
						</view>
						<view class="btnsView">
							<button class="comKx" @click="goMatchBillDetail(b)">详情</button>
								<!-- 如果未付款可以取消订单（非报项） -->
								<button class="comKx" @click="cancelBill(b)" v-if="b.payStatus=='0'&&b.auditStatus=='0'&&b.payType!='2'">取消订单</button>
								<button class="greenKx" v-if="b.payType!='2'&&b.payStatus=='0'&&b.auditStatus=='0'" @click="goPay(b)">继续付款</button>
				
						</view>
					</view>
				</uni-collapse-item>
			</uni-collapse>
			<view style="padding: 30rpx 30rpx 60rpx;" v-show="total2>10">
				<uni-pagination :show-icon="true" :total="total2"  @change="changePagination2" pageSize='10' :current="queryParam2.pageNum" title="标题文字" />
			</view>
			<view class="nodata" v-if="billList.length==0">
				<image mode="aspectFit" src="/static/nodata.png"></image>
				<text>还没有赛事订单</text>
			</view>
			
		</view>

		<uni-popup ref="searchPop" type="bottom" background-color="#fff">
			<view class="popTT">筛选</view>
			<view class="popBody">
				<uni-form :modelValue="queryParam" label-position="top" v-if="current==0">
					<uni-forms-item label="赛事时间">
						<uni-datetime-picker v-model="cptPeriodArr" type="datetimerange"/>
					</uni-forms-item>
					<view class="searchBtns">
						<button class="btn btnGray" @click="reset">重置</button>
						<button class="btn btn1" @click="search">查询</button>
					</view>
				</uni-form>
				<uni-form :modelValue="queryParam" label-position="top" v-if="current==1">
					<uni-forms-item label="状态">
						<uni-data-select  v-model="queryParam.payStatus" :localdata="billStatusList" ></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="付款时间">
						<uni-datetime-picker v-model="payTimeArr" type="daterange"/>
					</uni-forms-item>
					<uni-forms-item label="下单时间">
						<uni-datetime-picker v-model="commitTimeArr" type="daterange"/>
					</uni-forms-item>
					<view class="searchBtns">
						<button class="btn btnGray" @click="reset">重置</button>
						<button class="btn btn1" @click="searchBill">查询</button>
					</view>
				</uni-form>
			</view>
		</uni-popup>

		<uni-popup ref="popPayType" type="bottom" :is-mask-click="false" safe-area background-color="#fff">
			<view class="PopcloseBtn" @click="alertGiveup">
				<uni-icons type="closeempty" size="30" color="#999"></uni-icons>
			</view>
		
			<view class="rrcard" style="padding-bottom: 100rpx;">
				<view class="moneyNum">￥<text>{{finialFee}}</text></view>
				<view class="t">支付方式</view>
				<view class="whitebg">
					<radio-group @change="payChange">
						<!-- 支付方式 0 会员卡支付 1 微信支付 2 线下支付 -->
						<label class="uni-list-cell uni-list-cell-pd">
							<view class="littleimgBox">
								<image class="littleimg" src="@/static/zf01.png"></image>微信支付
							</view>
							<view>
								<radio checked="checked" value="1" />
							</view>
						</label>
						<label class="uni-list-cell uni-list-cell-pd">
							<view class="littleimgBox">
								<image class="littleimg" src="@/static/zf02.png"></image>会员卡支付(余额：￥{{myBalance}})
							</view>
							<view>
								<radio checked="checked" value="0" />
							</view>
						</label>
						<label class="uni-list-cell uni-list-cell-pd">
							<view class="littleimgBox">
								<image class="littleimg" src="@/static/zf03.png"></image>线下支付
							</view>
							<view>
								<radio checked="checked" value="2" />
							</view>
						</label>
					</radio-group>
				</view>
			
				<button class="payBtn" @click="pay">确认交易</button>
			</view>
		</uni-popup>
		<uni-popup ref="giveup" type="dialog">
			<uni-popup-dialog type="success" confirmText="放弃" cancelText="继续支付" content="是否放弃本次支付" @confirm="cancelPay"  @close="closeGiveup">
			</uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="payMationPop" :is-mask-click="false">
			<view class="payMationPopBody">
				<view class="t">线下支付</view>
				<view @click="copyOrg(organizerInfo)" class="hoverBg">
					<view class="p">公司：<text>{{organizerInfo.organizerName}}</text></view>
					<view class="p">开户：<text>{{organizerInfo.organizerBank}}</text></view>
					<view class="p">账号：<text>{{organizerInfo.organizerAccount}}</text></view>
					<view class="p">应付：<text class="orange">{{organizerInfo.organizerFee}}元</text></view>
				</view>
		
				<view @click="copyOrg(platformInfo)" v-if="platformInfo" class="hoverBg" style="margin: 40rpx 0 0;">
					<view class="p">公司：<text>{{platformInfo.platformName}}</text></view>
					<view class="p">开户：<text>{{platformInfo.platformBank}}</text></view>
					<view class="p">账号：<text>{{platformInfo.platformAccount}}</text></view>
					<view class="p">应付：<text class="orange">{{platformInfo.platformFee}}元</text></view>
				</view>
		
				<button class="btn btn1" @click="tipForPayMation">确定</button>
			</view>
		</uni-popup>
	</view>

</template>

<script setup>
	import { reactive, toRefs,getCurrentInstance} from 'vue';
	import * as match from '@/common/match.js';
	import * as api from '@/common/api.js';
	import { onShow,onReady} from '@dcloudio/uni-app';
	const data = reactive({
		items:['报项','订单'],
		// 0 未支付  1 线下支付待核销  2 付款中 3 线下支付已核销/已支付 4 退款中 5 已退款 6 线下退款待核销
		billStatusList:[{ value:-1, text: "全部" },{ value:0, text: "待支付" },{ value: 1, text: "待核销" },{ value: 3, text: "已支付" },{ value: 5, text: "已退款" }],
		queryParam:{
			name:'',
			cptPeriod:'',
			pageNum:1,
			pageSize:10
		},
		queryParam2:{
			cptName:'',
			payTimeRange:'',
			createTimeRange:'',
			pageNum:1,
			pageSize:10
		},
		list:[],
		current:0,
		billList:[],
		cptPeriodArr:[],
		payTimeArr:[],
		commitTimeArr:[],
		searchPop:null,
		popPayType:null,
		payMationPop:null,
		time:'',
		myBalance:'',
		finialFee:'',
		giveup:null,
		payType:'2',
		organizerInfo:{},
		platformInfo:{},
		total:0,
		total2:0,
		activeColor:'#e17b74'
	})
	const { items, queryParam,queryParam2,list,current,billList,payTimeArr,commitTimeArr,cptPeriodArr,
	searchPop,popPayType,payMationPop,billStatusList,time,myBalance,finialFee,payType,giveup,
	organizerInfo,platformInfo,total,total2,activeColor} = toRefs(data);
	const currUser = uni.getStorageSync('currUser');
	onShow(()=>{
		getList()
		getBillList()
		console.log(uni.getStorageSync('nowOpenId'))
	})
	function changePagination(e){
		queryParam.value.pageNum = e.current
		getList()
	}
	function changePagination2(e){
		queryParam2.value.pageNum = e.current
		getBillList()
	}
	function getList(){
		if(cptPeriodArr.value){
			queryParam.value.cptPeriod = cptPeriodArr.value.toString()
		}
		match.getMySignCptList(queryParam.value).then(res=>{
			list.value = res.rows
			total.value = res.total
		})
	}
	function getBillList(){
		queryParam2.value.cptName = queryParam.value.name||''
		queryParam2.value.payTimeRange = payTimeArr.value.toString()
		queryParam2.value.createTimeRange = commitTimeArr.value.toString()
		match.getMyOrderList(queryParam2.value).then(res=>{
			billList.value = res.rows
			total2.value = res.total
		})
	}
	function goSignDetail(item){
		uni.navigateTo({
			url: `/pages/usercenter/matchSignDetail?id=${item.id}&groupId=${item.signList[0]?.groupId||0}&auditStatus=${item.auditStatus}&payStatus=${item.payStatus}`
		});
	}
	function goMatchBillDetail(item){
		uni.navigateTo({
			url: `/pages/usercenter/matchBillDetail?id=${item.id}`
		});
	}
	function onClickItem(e){
		current.value = e.currentIndex
		if(current.value==0){
			getList()
		}else{
			getBillList()
		}
		queryParam.value = {}
	}
	function bindTimeChange(e){
		time.value = e.detail.value
	}
	function showSearchPop(){
		searchPop.value.open()
	}
	function onconfirm(){
		if(current.value==0){
			getList()
		}else{
			getBillList()
		}
	}
	function onclear(){
		queryParam.value.name = ''
		if(current.value==0){
			getList()
		}else{
			getBillList()
		}
	}
	function search(){
		getList()
		searchPop.value.close()
	}
	function searchBill(){
		getBillList()
		searchPop.value.close()
	}
	function reset(){
		cptPeriodArr = []
		commitTimeArr = []
		payTimeArr = []
		queryParam.value = {}
		queryParam2.value = {}
		getList()
	}
	let thisBill = {}
	function goPay(b){
		// 获取会员卡余额
		api.getMyBalance().then((res) => {
			myBalance.value = res.data
		})
		popPayType.value.open()
		thisBill = b
		finialFee.value = b.totalAmount
	}
	function payChange(evt) {
		payType.value = evt.detail.value
	}
	function alertGiveup(){
		giveup.value.open()
	}
	function closeGiveup(){
		giveup.value.close()
	}
	function cancelPay(){
		// 点击放弃
		popPayType.value.close()
	}
	function tipForPayMation(){
		uni.showModal({
			title: '提示',
			content: '点击信息复制到剪贴板',
			cancelText:'好的',
			confirmText:'我已复制',
			success: function (res) {
				if (res.confirm) {
					// 去订单详情页
					payMationPop.value.close()
				} else if (res.cancel) {
					console.log('返回');
				}
			}
		});
	}
	function copyOrg(info){
		let str = `公司：${info.organizerName}；开户行：${info.organizerBank}；账户：${info.organizerAccount}；`
		uni.setClipboardData({
			data: str,
			success: function () {
				console.log('success');
			}
		});
	}
	function pay(){
		// 继续支付
		const nowOpenId = uni.getStorageSync('nowOpenId');
		if(payType.value==''){
			uni.showToast({
				title: '请选择支付方式',
				icon:'none',
				duration: 2000
			});
			return
		}
		if(payType.value=='1'){
			uni.showLoading({
				title: '支付中...'
			});
			let obj = {
				orderId:thisBill.id,
				platformType: 0,
				payType:1,
				openId:nowOpenId
			}
			match.payMatch(obj).then(res=>{
				if (res.data.weixinData) {
					wePay(res.data.weixinData)
				} else {
					uni.showToast({
						title: '支付成功',
						duration: 2000
					});
				}
			}).catch(() => {
				uni.showToast({
					title: '支付失败,请稍后重试',
					duration: 2000
				});
			}).finally(() => {
				uni.hideLoading()
				popPayType.value.close()
				getList()
				getBillList()
			})
			
		} else {
			match.payMatch({orderId:thisBill.id,payType:payType.value}).then(res=>{
				thisBill = {}
				finialFee.value = '0'
				if(res.data.success=='1'){
					console.log('支付成功')
					popPayType.value.close()
					getList()
					getBillList()
					if(payType.value=='2'){
						// 线下支付
						organizerInfo.value = res.data.org
						platformInfo.value = res.data.plat
						payMationPop.value.open()
					} else {
						uni.showToast({
							title: '支付成功',
							duration: 2000
						});
					}
			
				}else{
					uni.showToast({
						title: '支付失败，请稍后重试',
						icon:'none',
						duration: 2000
					});
				}
			})
		}
	}
	function wePay(configdata){
		// 微信支付
		uni.requestPayment({
			"provider": "wxpay",
			"appId": configdata.appId,
			"nonceStr": configdata.nonceStr,
			"package": configdata.packageValue, // 随机字符串
			"timeStamp": configdata.timeStamp, // 时间戳（单位：秒）
			"signType": configdata.signType, // 签名，这里用的 MD5/RSA 签名
			"paySign": configdata.paySign,
			success(res) {
				uni.showToast({
					title: '支付成功',
					icon: 'none',
					duration: 2000
				})
				match.maPayConfirm({
					orderId:thisBill.id,
					successFlag:true
				}).then((res)=>{
					
				})
				popPayType.value.close()
				getBillList()
			},
			fail(e) {
				uni.showToast({
					title: '支付取消',
					icon: 'none',
					duration: 2000
				})
				match.maPayConfirm({
					orderId:thisBill.id,
					successFlag:false
				}).then((res)=>{
					
				})
				popPayType.value.close()
				getBillList()
			}
		})
	}
	
	function cancelBill(b){
		uni.showModal({
			title: '提示',
			content: '确定取消吗',
			success: function (res) {
				if (res.confirm) {
					match.cancelMyUnPayedOrder(b.id).then(Response=>{
						console.log(Response.data)
						// 刷新数据
						getBillList()
						getList()
					})
					
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});

	}
</script>

<style lang="scss" scoped>
	.topSearch{ display: flex; align-items: center;}
	.bgWhite{background: #fff;}
	.popTT{text-align: center;    padding: 30rpx 0 0;}
	.popBody{background: #fff;padding: 30rpx;height:50vh}
	.searchBtns{display: flex;}
	.btnGray{color: #1B1B1B;background: #F5F7F9;}
	.billcontent{
		:deep(.uni-collapse){background-color: transparent;    margin: 30rpx; width: 700rpx;}
		:deep(.uni-collapse-item){ position: relative;}
	}
	.baoItem{
		.bold{color: #2B3133;font-weight: 500;font-size: 30rpx;margin: 0 0 20rpx;}
		.pp{font-size: 28rpx;color: #7B7F83;padding: 10rpx 0;
			text{color: #2B3133;float: right;}
		}
		.orange{font-size: 26rpx;}
		button{border-radius: 60rpx;line-height: 60rpx;font-size: 28rpx;background:#fff;margin: 0 0 0 25rpx;}
		.btnsView{display: flex;justify-content: flex-end;margin: 34rpx 0 0;}
		.comKx{color: #0D0D0D;border: 1rpx solid #D2D7D9;}
		.greenKx{color: #00C176;border: 1rpx solid #00C176;}
	}
	:deep(.uni-collapse-item__title-arrow ){position: absolute; right: 0;top: 20rpx; line-height: 20px;}
	.littleimgBox {
		display: flex;
		align-items: center;
	}
	
	.littleimg {
		width: 50rpx;
		height: 50rpx;
		margin-right: 15rpx;
	}
	.payMationPopBody{background: #FFFFFF;    width: 550rpx; border-radius: 15px; padding: 50rpx;box-sizing: border-box;
		.t{text-align: center;color: #7B7F83;font-size: 34rpx;margin:0 0 50rpx;}
		.p{color: #7B7F83;font-size: 30rpx;
			text{color: #1A1A1A;}
		}
		.btn{margin-top:60rpx;}
	}
	.payBtn{    margin: 100rpx 0;}
</style>
